package cn.manyufun.myf.ui.comics.activity;

import android.Manifest;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import cn.manyufun.myf.R;
import cn.manyufun.myf.api.Api;
import cn.manyufun.myf.api.HostType;
import cn.manyufun.myf.app.AppConstant;
import cn.manyufun.myf.bean.BaseBean;
import cn.manyufun.myf.common.base.BaseActivity;
import cn.manyufun.myf.common.baserx.RxSchedulers;
import cn.manyufun.myf.common.baserx.RxSubscriber;
import cn.manyufun.myf.common.commonutils.APIUtils;
import cn.manyufun.myf.common.commonutils.ImageLoaderUtils;
import cn.manyufun.myf.common.commonutils.LogUtils;
import cn.manyufun.myf.common.commonutils.ToastUtil;
import cn.manyufun.myf.common.commonutils.UserInfoUtils;
import cn.manyufun.myf.common.commonwidget.NormalTitleBar;
import cn.manyufun.myf.widget.actionsheet.ActionSheet;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

import static cn.manyufun.myf.app.AppConstant.REQUEST_CODE_READ_EXTERNAL_STORAGE;
import static cn.manyufun.myf.common.commonutils.RequestBodyUtils.toRequestBody;

public class EditArticleActivity extends BaseActivity implements View.OnClickListener {
    public static final String INTENT_KEY = "COMICS";
    private long mComicsID;
    @BindView(R.id.ntb)
    NormalTitleBar ntb;
    @BindView(R.id.et_title)
    EditText mEtTitle;
    @BindView(R.id.et_content)
    EditText mEtContent;
    @BindView(R.id.upload_img)
    ImageView mImgUpload;


    private Uri photoUri;
    private File mHeadfile;
    public static void startAction(Context context, Bundle bundle) {
        Intent intent = new Intent(context, EditArticleActivity.class);
        if (bundle != null)
            intent.putExtras(bundle);

        context.startActivity(intent);
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_edit_article;
    }

    @Override
    public void initPresenter() {

    }

    @Override
    public void initView() {
        mComicsID = getIntent().getLongExtra(INTENT_KEY, 0);
        ntb.setTitleText("写漫评");
        ntb.setRightTitle("发布");
        ntb.setRightTitleVisibility(true);
        ntb.setOnBackListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        ntb.setOnRightTextListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                String content = mEtContent.getText().toString();
//                String title = mEtTitle.getText().toString();
//                if (TextUtils.isEmpty(content) || TextUtils.isEmpty(title)) {
//                    ToastUtil.showLong("请输入标题或评论内容！");
//                    return;
//                }
//                Api.getDefault(HostType.manyufun).setArticleNew(getArticleNewRequestBody())
//                        .compose(RxSchedulers.<BaseBean>io_main())
//                        .subscribe(new RxSubscriber<BaseBean>(EditArticleActivity.this, false) {
//                            @Override
//                            public void onStart() {
//                                super.onStart();
//                            }
//
//                            @Override
//                            protected void _onNext(BaseBean posterBean) {
//                                if (posterBean.getSuccess().equals("1")) {
//                                    ToastUtil.show("提交成功", 3);
//                                    mRxManager.post(AppConstant.COMICS_EDIT_COMMENT_OR_ARTICLE, null);
//                                    finish();
//                                } else {
//                                    ToastUtil.show(posterBean.getErrorMsg(), 3);
//                                }
//                            }
//
//                            @Override
//                            protected void _onError(String message) {
//
//                            }
//                        });
                createArticleWithImage();
            }
        });
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            int checkReadStoragePermission = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE);
            int checkCameraPermission = ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA);
            if (checkCameraPermission != PackageManager.PERMISSION_GRANTED || checkReadStoragePermission != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.CAMERA}, REQUEST_CODE_READ_EXTERNAL_STORAGE);
            } else {
                mImgUpload.setOnClickListener(this);
            }
        } else {
            mImgUpload.setOnClickListener(this);
        }
    }

    private void createArticleWithImage() {
        String content = mEtContent.getText().toString();
        String title = mEtTitle.getText().toString();
        if (TextUtils.isEmpty(content) || TextUtils.isEmpty(title)) {
            ToastUtil.showLong("请输入标题或评论内容！");
            return;
        }

        MultipartBody.Part body = null;
        if (mHeadfile != null) {
            RequestBody requestBody = RequestBody.create(MediaType.parse("image/*"), mHeadfile);
            body = MultipartBody.Part.createFormData("image", mHeadfile.getName(), requestBody);
        } else {
            ToastUtil.showLong("请设置漫评头部图片！");
            return;
        }
        Map<String, RequestBody> bodyMap = new HashMap<>();
        bodyMap.put("UserToken", toRequestBody(UserInfoUtils.getInstance().getToken()));
        bodyMap.put("Title", toRequestBody(title));
        bodyMap.put("Content", toRequestBody(content + ""));
        bodyMap.put("ComicId", toRequestBody(mComicsID + ""));


        Api.getDefault(HostType.manyufun).articleCreate(bodyMap, body)
                .compose(RxSchedulers.<BaseBean>io_main())
                .subscribe(new RxSubscriber<BaseBean>(EditArticleActivity.this, false) {
                    @Override
                    public void onStart() {
                        super.onStart();
                    }

                    @Override
                    protected void _onNext(BaseBean posterBean) {
                        if (posterBean.getSuccess().equals("1")) {
                            ToastUtil.show("提交成功", 3);
                            mRxManager.post(AppConstant.COMICS_EDIT_COMMENT_OR_ARTICLE, null);
                            finish();
                        } else {
                            ToastUtil.show(posterBean.getErrorMsg(), 3);
                        }
                        LogUtils.logd("xwx_modify:" + posterBean.getSuccess() + "|" + posterBean.getErrorCode());
                    }

                    @Override
                    protected void _onError(String message) {
                        LogUtils.logd("xwx_modifyerror:" + message);
                    }
                });
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        switch (requestCode) {
            case REQUEST_CODE_READ_EXTERNAL_STORAGE:
                boolean flag = true;
                for (int grantResult : grantResults) {
                    if (grantResult != PackageManager.PERMISSION_GRANTED) {
                        flag = false;
                        break;
                    }
                }
                if (flag) {
                    mImgUpload.setOnClickListener(this);
                } else {
                    mImgUpload.setVisibility(View.GONE);
                    mImgUpload.setOnClickListener(null);
                    Toast.makeText(this, "没有该权限无法添加图片！", Toast.LENGTH_SHORT)
                            .show();
                }
                break;
            default:
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }
    private RequestBody getArticleNewRequestBody() {
        JSONObject root = new JSONObject();
        JSONObject head = APIUtils.getHeadParamter();
        try {
            root.put("Head", head);
            root.put("Title", mEtTitle.getText().toString());
            root.put("Content", mEtContent.getText().toString());
            root.put("ComicId", mComicsID);
            root.put("CoverImageUrl", "");
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return RequestBody.create(MediaType.parse("application/json"), root.toString());
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        if (hasFocus) {
            Timer timer = new Timer();
            timer.schedule(new TimerTask() {

                public void run() {
                    InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                    inputMethodManager.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
                }
            }, 200); // 秒后自动弹出

        }
    }

    @Override
    public void onClick(View view) {
        upload_images();
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == AppConstant.RESULT_LOAD_IMAGE || requestCode == AppConstant.RESULT_LOAD_CAMERA) {
            String picturePath = "";
            Uri selectedImage = null;
            if (requestCode == AppConstant.RESULT_LOAD_IMAGE && resultCode == RESULT_OK && data != null) {
                selectedImage = data.getData();
            } else if (requestCode == AppConstant.RESULT_LOAD_CAMERA) {
                selectedImage = photoUri;
            }
//            根据图库返回的数据类型分别处理（比如小米的照片文件夹返回的就是file类型，其他图片返回的时content类型，需要另外处理）
            if (selectedImage == null) {
                return;
            }
            if (selectedImage.getScheme().equals("file")) {
                picturePath = selectedImage.toString().replace("file://", "");
            } else if (selectedImage.getScheme().equals("content")) {
                String[] filePathColumn = {MediaStore.Images.Media.DATA};
                Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
                if (cursor == null) //throw new NullPointerException("没找到照片");
                    return;
                if (cursor.moveToFirst()) {
                    int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                    picturePath = cursor.getString(columnIndex);
                }
                cursor.close();
            }
            if (!picturePath.equals("")) {
                File file = new File(picturePath);
                if (!file.exists()) {
                    return;
                }
//                先释放内存

                lubanCompress(picturePath);//CompressUtils.Compress(this, picturePath, Bitmap.CompressFormat.JPEG, 800);

            }
        }
    }

    private void lubanCompress(String path) {
        Luban.with(this)
                .load(path)
                .ignoreBy(100)
                .setTargetDir(getPath())
                .setCompressListener(new OnCompressListener() {
                    @Override
                    public void onStart() {
                        LogUtils.logd("xwx commpress start.");
                    }

                    @Override
                    public void onSuccess(File file) {
                        compressSuccess(file);
                    }

                    @Override
                    public void onError(Throwable e) {

                        LogUtils.logd("xwx commpress error." + e.toString());
                    }
                }).launch();

    }

    private void compressSuccess(File file) {
        mHeadfile = file;
        ImageLoaderUtils.display(this, mImgUpload, file);
//        mIvUserLogo.setImageBitmap(BitmapFactory.decodeFile(image_file));
    }

    private String getPath() {
        String path = Environment.getExternalStorageDirectory() + "/myf/compressimage/";
        File file = new File(path);
        LogUtils.logd("xwx commpress get path." + path);
        if (file.mkdirs()) {
            return path;
        }
        return path;
    }

    private void clearImg() {
//        if (mImgUpload.getDrawable() != null) {
//            Bitmap bitmap = ((BitmapDrawable) mImgUpload.getDrawable()).getBitmap();
//            if (bitmap != null && !bitmap.isRecycled()) {
//                bitmap.recycle();
//                bitmap = null;
//                System.gc();
//            }
//            mImgUpload.setImageBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.upload_img));
        ImageLoaderUtils.simpleDisplay(this, mImgUpload, R.drawable.upload_img);
//        }
        mHeadfile = null;
    }

    private void upload_images() {
        if (mHeadfile != null) {
            android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(this);
            builder.setMessage("确定要删除照片吗");
            builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });
            builder.setPositiveButton("删除", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    clearImg();
                    dialog.dismiss();
                }
            });
            builder.create().show();
        } else {
            final ActionSheet actionSheet = new ActionSheet(this);
            actionSheet.show("选择图片来源", new String[]{"拍照", "从相册选择"}, new cn.manyufun.myf.widget.actionsheet.Method.Action1<Integer>() {
                @Override
                public void invoke(Integer index) {
                    actionSheet.hide();
                    if (index == 0) {
                        String sdState = Environment.getExternalStorageState();
                        if (!sdState.equals(Environment.MEDIA_MOUNTED)) {
                            Toast.makeText(EditArticleActivity.this, "没有存储卡", Toast.LENGTH_LONG).show();
                            return;
                        }
                        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                        ContentValues values = new ContentValues();
                        photoUri = EditArticleActivity.this.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
                        intent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
                        startActivityForResult(intent, AppConstant.RESULT_LOAD_CAMERA);
                    } else if (index == 1) {
                        Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                        startActivityForResult(intent, AppConstant.RESULT_LOAD_IMAGE);
                    }
                }
            });
        }
    }
}
